package operate.rw;

/**
 * @author zxc
 */
public class Writer extends OSThread implements Runnable {
    private final Semaphore rwMutex;
    private final Semaphore wMutex;

    public Writer(Semaphore rwMutex, Semaphore wMutex, double delay, double persist) {
        super(delay, persist);
        this.rwMutex = rwMutex;
        this.wMutex = wMutex;
    }


    public void run() {
        String name = "Writer thread " + Thread.currentThread().getName();
        try {
            Thread.sleep((long) (super.getDelay() * INTE_PER_SEC));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " sents the reading require !");

        wMutex.p();
        rwMutex.p();

        // 执行写操作
        System.out.println(name + " begins to read file !");
        try {
            Thread.sleep((long) (super.getPersist() * INTE_PER_SEC));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        rwMutex.v();
        wMutex.v();

        System.out.println(name + " finished reading file !");
    }
}